const { Chapter, Course, Attachment } = require("../../models");
const { Op } = require("sequelize");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");
const {
  deleteFileAttachmentByBusinessId,
} = require("../upload/attachmentService");

/**
 * 获取章节列表
 * @param req
 * @returns {Promise<{count: number, pageSize: number, rows: Model[], currentPage: number}>}
 */
exports.list = async (req) => {
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // if (!query.courseId) {
    //   throw new Error("获取章节列表失败,课程Id不能为空.");
    // }
    // 排序+分页
    const condition = {
      ...getCondition(),
      order: [
        ["rank", "ASC"],
        ["id", "ASC"],
      ],
      limit: pageSize,
      offset: offset,
    };

    // 模糊查询
    if (query.title) {
      condition.where = {
        title: {
          [Op.like]: `%${query.title}%`,
        },
      };
    }

    // 模糊查询
    if (query.courseId) {
      condition.where = {
        courseId: {
          [Op.eq]: query.courseId,
        },
      };
    }
    // 分页查询
    const { count, rows } = await Chapter.findAndCountAll(condition);
    // 返回
    return { count, rows, currentPage, pageSize };
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 创建章节
 * @param body
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.create = async (body) => {
  try {
    return await Chapter.create(body);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 删除章节
 * DELETE /chapters/:id
 */
exports.delete = async (id) => {
  try {
    const chapter = await this.getChapter(id);
    await deleteFileAttachmentByBusinessId(id);
    await chapter.destroy();
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 更新章节
 * @param id
 * @param body
 * @returns {Promise<Model<*, TModelAttributes>>}
 */
exports.update = async (id, body) => {
  try {
    const chapter = await this.getChapter(id);
    return await chapter.update(body); //删除
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取当前章节
 * @param id
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.getChapter = async (id) => {
  const condition = getCondition();
  // 获取当前章节
  const chapter = await Chapter.findByPk(id, condition);
  if (!chapter) {
    throw new NotFoundError(`ID: ${id} not found`);
  }
  return chapter;
};

/**
 * 关联课程数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
function getCondition() {
  return {
    attributes: { exclude: ["CourseId"] },
    include: [
      {
        model: Course,
        as: "course",
        attributes: ["id", "name"],
      },
      {
        model: Attachment,
        as: "attachments",
        attributes: ["id"],
      },
    ],
  };
}
